package com.infinit.easyreader.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * 类：com.infinit.easyreader.utils.BitmapUtils V[1.0.0]
 * 作用：对bitmap进行操作的工具类
 * Created by rzy on 2016/5/20.
 */
public class BitmapUtils {


    /**
     * 作用，获取bitmap的缩放比例，方法源自Google
     *
     * @param options   指定的options
     * @param reqWidth  需要的宽度
     * @param reqHeight 需要的高度
     * @return sampleSize
     */
    public int calculateInSampleSize(BitmapFactory.Options options,
                                     int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public Bitmap getSampledBitmap(int resId, int reqHeight, int reqWidth, Context context) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeResource(context.getResources(), resId, options);
        return bitmap;
    }


}
